	var choiseClientGridStore = new Ext.data.JsonStore({
		url : "/flats/manager/get_clients.do",
		fields : ["lastName","firstName","patronymik","phone","email","id"],
		root : "clients",
		totalProperty: 'count'
	});
	
	var choisenClientIndex = new Ext.form.Field({
		hidden : true
	});
	
	var choiseClientGrid = new Ext.grid.GridPanel({	
		store : choiseClientGridStore,	
		columnLines : true,	
		height : 500,	
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex:'lastName',header:'Фамилия'},
		           {sortable : true,dataIndex:'firstName',header:'Имя'},
		           {sortable : true,dataIndex:'patronymik',header:'Отчество'},
		           {sortable : true,dataIndex:'email',header:'E-mail'},
		           {sortable : true,dataIndex:'phone',header:'Телефон'},
		           {dataIndex : 'id',hidden : true,hideable:false}],
		bbar : new Ext.PagingToolbar({
			pageSize : 20,
			store : choiseClientGridStore
		}),
		selModel : new Ext.grid.RowSelectionModel({
			singleSelect : true,
			listeners : {
				rowselect : {
					fn  :function(sm,index,record) {
						choisenClientIndex.setValue(index);
					}
				}
			}
		}),
		listeners : {
			dblclick : function() {
				var data = choiseClientGridStore.getAt(choisenClientIndex.getValue()).data;
				var actionType = whatAddWindowShows.getValue();
				if (actionType == "buy") {
					 Ext.getCmp("addBuyAppClientId").setValue(data.id);
					 Ext.getCmp("addBuyAppLastName").setValue(data.lastName);
					 Ext.getCmp("addBuyAppFirstName").setValue(data.firstName);
					 Ext.getCmp("addBuyAppPatronymik").setValue(data.patronymik);
					 Ext.getCmp("addBuyAppPhone").setValue(data.phone);
					 Ext.getCmp("addBuyAppEmail").setValue(data.email);				
					 choiseClientWindow.hide();
				} else {
					 Ext.getCmp("addSaleAppClientId").setValue(data.id);
					 Ext.getCmp("addSaleAppLastName").setValue(data.lastName);
					 Ext.getCmp("addSaleAppFirstName").setValue(data.firstName);
					 Ext.getCmp("addSaleAppPatronymik").setValue(data.patronymik);
					 Ext.getCmp("addSaleAppPhone").setValue(data.phone);
					 Ext.getCmp("addSaleAppEmail").setValue(data.email);
					 choiseClientWindow.hide();
				}
			}
		}
	});
	
	var createClientButton = new Ext.Button({text : "Добавить",
			 handler : function() {			    	  							 
					 if (createClientForm.getForm().isValid()) {
						 createClientForm.getForm().submit({
							 success : function(request,response){ 
								 var data = Ext.decode(response.response.responseText);
								 if (!data.errors) {
									 if (!data.contains) {
										 if (data.added) {
											 var actionType = whatAddWindowShows.getValue();
											 if (actionType == "buy") {
												 Ext.getCmp("addBuyAppClientId").setValue(data.client.id);
												 Ext.getCmp("addBuyAppLastName").setValue(data.client.lastName);
												 Ext.getCmp("addBuyAppFirstName").setValue(data.client.firstName);
												 Ext.getCmp("addBuyAppPatronymik").setValue(data.client.patronymik);
												 Ext.getCmp("addBuyAppPhone").setValue(data.client.phone);
												 Ext.getCmp("addBuyAppEmail").setValue(data.client.email);
												 createClientWindow.hide();
												 choiseClientWindow.hide();
											 } else {
												 Ext.getCmp("addSaleAppClientId").setValue(data.client.id);
												 Ext.getCmp("addSaleAppLastName").setValue(data.client.lastName);
												 Ext.getCmp("addSaleAppFirstName").setValue(data.client.firstName);
												 Ext.getCmp("addSaleAppPatronymik").setValue(data.client.patronymik);
												 Ext.getCmp("addSaleAppPhone").setValue(data.client.phone);
												 Ext.getCmp("addSaleAppEmail").setValue(data.client.email);
												 createClientWindow.hide();
												 choiseClientWindow.hide();
											 }
										 } else {
											 Ext.Msg.alert("Ошибка","Не могу добавить клиента. Попробуйже позже.");
										 }
									 } else {
										 Ext.Msg.alert("Ошибка","Клиент уже сущетсвует.");
									 }
								 } else {
									 Ext.Msg.alert("Ошибка","Форма заполнена неверно!");
								 }
								 
							 }
						 });
					 }
				 }					 					    	  
	});
	
	var createClientForm = new Ext.FormPanel({
				url : "/flats/manager/add_client.do",
				method : "post",
				autoHeight : true,
				border : false,
				bodyStyle : "padding:10px;background-color:#CCD8E7",
				items : [new Ext.form.TextField({fieldLabel: "Фамилия",										 
											     width : 210,
											     allowBlank : false,
											     vtype : "name",
											     maxLength : 30,		
											     name : "lastName"}),
					     new Ext.form.TextField({fieldLabel : "Имя", 					 
					    	 					 name : "firstName",
					    	 					 maxLength : 30,		
					    	 					 allowBlank : false,
					    	 					 vtype : "name",
					    	 					 width : 210}),
					     new Ext.form.TextField({fieldLabel : "Отчество",
					    	 		             name : "patronymik",
					    	 		             vtype : "name",
					    	 		             maxLength : 30,		
					    	 		             allowBlank : false,					 							    	 		             
					    	 		             width : 210}),
					     new Ext.form.TextField({fieldLabel : "Телефон",
					    	 					 name : "phone",
					    	 					 maxLength : 15,		
					    	 					 allowBlank : false,
					    	 					 vtype : "phone",
					    	 					 width : 210}),
					     new Ext.form.TextField({fieldLabel : "E-mail",
					    	 					 name : "email",
					    	 					 vtype : "email",
					    	 					 maxLength : 40,		
					    	 					 allowBlank : false,
					    	 					 width : 210})],
	  	         buttons : [createClientButton]
	});
	
	var createClientWindow = new Ext.Window({
		layout : 'fit',
		title : 'Добавить нового клиента',
		closeAction : 'hide',	
		bodyStyle : "background-color:#CCD8E7",
		y : 50,
		width : 350,
		autoHeight : true,
		border : false,
		modal : true,
		items : [new Ext.Panel({border : false,
								bodyStyle : "background-color:#CCD8E7",
								autoHeight : true,
					 			items : [createClientForm]})]					 			   
	});
	
	var choiseClientPanel = new Ext.Panel({
		border : false,
		autoHeight : true,
		items : [new Ext.Panel({border :false,
								tbar:[new Ext.Button({text : "Добавить клиента",
													  handler : function() {
														  createClientForm.getForm().reset();
														  createClientWindow.show();
													  }
								})]}),
				 choiseClientGrid]
	});	
	
	var choiseClientWindow = new Ext.Window({
		layout : 'fit',
		title : 'Выберите клиента из списка',
		closeAction : 'hide',	
		y : 50,
		width : 700,
		autoHeight : true,
		border : false,
		modal : true,
		items : [choiseClientPanel]
	});
	
	var whatAddWindowShows = new Ext.form.Field({
		hidden : true
	});
	
	var districtsComboBox = comboBoxFactory.createDistrictComboBox("district.id");
	var addSaleDistrictsComboBox = comboBoxFactory.createDistrictComboBox("flat.district.id");
		
	var addSaleApplicationForm = new Ext.FormPanel({
		url : "/flats/manager/add_sale_application.do",
		border : false,
		bodyStyle : "padding:10px;background-color:#CCD8E7",
		items : [new Ext.form.Field({hidden:true,
		        	 				 name:"client.id",
		        	 				 id : "addSaleAppClientId"}),
		         new Ext.form.TextField({fieldLabel: "Фамилия",
										 readOnly : true,
										 id : "addSaleAppLastName",
										 width : 210}),
				 new Ext.form.TextField({fieldLabel : "Имя",
					 					 readOnly : true,
					 					 id : "addSaleAppFirstName",
					 					 width : 210}),
				 new Ext.form.TextField({fieldLabel : "Отчество",
					 				     readOnly : true,
					 				     id : "addSaleAppPatronymik",
					 				     width : 210}),
				 new Ext.form.TextField({fieldLabel : "Телефон",
					 					 readOnly : true,
					 					 id : "addSaleAppPhone",
					 					 width : 210}),
				 new Ext.form.TextField({fieldLabel : "E-mail",
					 					 readOnly : true,
					 					 id : "addSaleAppEmail",
					 					 width : 210}),
				 new Ext.Button({text : "Выбрать клиента",
					 		     handler : function(){
					 		    	choiseClientGrid.getStore().load({params:{start:0,limit:20}});
					 		    	choiseClientWindow.show();
					 		     }}),{border : false,height : 20,bodyStyle : "background-color:#CCD8E7"},
			     addSaleDistrictsComboBox,
			     new Ext.form.NumberField({fieldLabel : "Цена",
			    	 					   width : 210,
			    	 					   name : "flat.price",
			    	 					   maxLength:10,
			    	 					   allowBlank : false}),
			     new Ext.form.TextField({fieldLabel : "Этаж",
 					 					 width : 210,
 					 					 maxLength:3,
 					 					 name : "flat.floor",
 					 					 vtype : "numeric",
 					 					 allowBlank : false}),
 			     new Ext.form.TextField({fieldLabel : "Этажность",
 			    	 					 width : 210,
 			    	 					 name : "flat.floors",
 			    	 					 maxLength:3,
 			    	 					 vtype : "numeric",
 			    	 					 allowBlank : false}),
 			     new Ext.form.TextField({fieldLabel : "Комнат",
 			    	 					 width : 210,
 			    	 					 name : "flat.rooms",
 			    	 					 vtype : "numeric",
 			    	 					 maxLength:1,
 			    	 					 allowBlank : false}),
 			     new Ext.form.NumberField({fieldLabel : "Площадь",
 			    	 					   name : "flat.square",
 			    	 					   maxLength:6,
 			    	 					   width : 210,
 			    	 					   allowBlank : false}),
 			     new Ext.form.NumberField({fieldLabel : "Жилая прощадь",
 			    	 					   width : 210,
 			    	 					   maxLength:6,
 			    	 					   name : "flat.livingSquare"}),
 			     new Ext.form.NumberField({fieldLabel : "Площадь кухни",
 			    	 					   name : "flat.cookSquare",
 			    	 					   maxLength:6,
 			    	 					   width : 210}),
 			     new Ext.form.TextField({fieldLabel : "Улица",
 			    	 					 name : "flat.street",
 			    	 					 width : 210,
 			    	 					 maxLength:30,
 			    	 					 allowBlank :false}),
 			     new Ext.form.TextField({fieldLabel : "Дом",
 			    	 					 width : 210,
 			    	 					maxLength:6,
 			    	 					 allowBlank : false,
 			    	 					 name : "flat.house",
 			    	 					 vtype :"address"}),
 			     new Ext.form.TextField({fieldLabel : "Квартира",
 			    	                     width : 210,
 			    	                     name : "flat.flat",
 			    	                    maxLength:6,
 			    	                     vtype :"address"})],
 			 buttons : [new Ext.Button({text : "Добавить",
 				 						handler : function() {
 				 							if (addSaleApplicationForm.getForm().isValid()) {
 				 								addSaleApplicationForm.getForm().submit({
 				 									success : function() {
 				 										Ext.Msg.alert("Добавлено","Заявка успешно добавлено!");
 				 									},
 				 									failure : function(request,response) {
 				 										var data = Ext.decode(response.response.responseText);
 				 										if (data.invalidForm) {
 				 											Ext.Msg.alert("Ошибка","Форма заполнена неверно!");
 				 										} else {
 				 											Ext.Msg.alert("Ошибка","Попробуйте позже!");
 				 										}
 				 									}
 				 								});
 				 							}
 				 						}}),
 				 		 new Ext.Button({text : "Отмена",
 				 			 			 handler : function() {
 				 			 				addSaleApplicationWindow.hide();
 				 			 			 }
 				 		 })]		   	                   
	
	});
	
	var addBuyApplicationForm = new Ext.FormPanel({
		url : "/flats/manager/add_buy_application.do",
		border : false,
		bodyStyle : "padding:10px;background-color:#CCD8E7",
		items : [new Ext.form.Field({hidden:true,
		        	 				 name:"client.id",
		        	 				 id : "addBuyAppClientId"}),
		         new Ext.form.TextField({fieldLabel: "Фамилия",
										 readOnly : true,
										 id : "addBuyAppLastName",
										 width : 210}),
				 new Ext.form.TextField({fieldLabel : "Имя",
					 					 readOnly : true,
					 					 id : "addBuyAppFirstName",
					 					 width : 210}),
				 new Ext.form.TextField({fieldLabel : "Отчество",
					 				     readOnly : true,
					 				     id : "addBuyAppPatronymik",
					 				     width : 210}),
				 new Ext.form.TextField({fieldLabel : "Телефон",
					 					 readOnly : true,
					 					 id : "addBuyAppPhone",
					 					 width : 210}),
				 new Ext.form.TextField({fieldLabel : "E-mail",
					 					 readOnly : true,
					 					 id : "addBuyAppEmail",
					 					 width : 210}),
				 new Ext.Button({text : "Выбрать клиента",
					 		     handler : function(){
					 		    	choiseClientGrid.getStore().load({params:{start:0,limit:20}});
					 		    	choiseClientWindow.show();
					 		     }}),{border : false,height : 20,bodyStyle : "background-color:#CCD8E7"},
				 districtsComboBox,
				 new Ext.form.TextField({fieldLabel : "Этаж",
					 					 width : 210,
					 					 name : "floor",
					 					 vtype : "numeric"}),
				 new Ext.form.NumberField({fieldLabel : "Цена от",
					 					   width : 210,
					 					   name : "priceFrom"}),
				 new Ext.form.NumberField({fieldLabel : "Цена до",
				 						   width : 210,
				 						   name : "priceTo",
				 						   allowBlank : false}),
				 new Ext.form.TextField({fieldLabel : "Комнат",
					 					 width : 210,
					 					 name : "rooms",
					 					 vtype : "numeric",
					 					 allowBlank:false})],
				 buttons : [new Ext.Button({text : "Добавить",
					 					    handler : function() {
					 					    	if (addBuyApplicationForm.getForm().isValid()){
					 					    		addBuyApplicationForm.getForm().submit({
					 					    			success : function() {
					 					    				Ext.Msg.alert("Добавлено","Заявка успешно добавлено!");
					 					    			},
					 					    			failure : function(request,response) {
					 					    				var data = Ext.decode(response.response.responseText);
					 					    				if (data.invalidForm) {
					 					    					Ext.Msg.alert("Ошибка","Форма заполнена неверно!");
					 					    				} else {
					 					    					Ext.Msg.alert("Ошибка","Попробуйте позже!");
					 					    				}
					 					    			}
					 					    		});
					 					    	}
					 					    }
				 			}),
				 			new Ext.Button({text : "Отмена",
				 						    handler : function() {
				 						    	addBuyApplicationWindow.hide();
				 						    }
				 			})]	
	});	
	
	var addBuyApplicationWindow = new Ext.Window({
		layout : 'fit',
		title : 'Добавить заявку для покупки',
		closeAction : 'hide',	
		y : 50,
		bodyStyle : "background-color:#CCD8E7",
		width : 350,
		height : 400,
		border : false,
		modal : true,
		items : [addBuyApplicationForm]
	});
	
	var addSaleApplicationWindow = new Ext.Window({
		border : false,
		layout : 'fit',
		title : 'Добавить заявку для продажи',
		closeAction : 'hide',
		bodyStyle : "background-color:#CCD8E7",
		y : 50,
		width : 350,
		height : 560,
		modal : true,
		items : [addSaleApplicationForm]
	});
	
	applicationTypeData = [{"display_type":"Покупка","type":"buy"},
	                       {"display_type":"Продажа","type":"sale"}];
	
	var applicationTypeComboBox = new Ext.form.ComboBox({
		store : new Ext.data.JsonStore({
					fields : [{name : "type"},{name : "display_type"}]
				}),	
		displayField : 'display_type',
		valueField : 'type',
		mode : 'local',
		emptyText :'Тип заявки',	
		fieldLabel : 'Заявка'		
	});
	
	var applicationTypeForm = new Ext.FormPanel({
		bodyStyle : "padding:10px;background-color:#CCD8E7",		
		border : false,
		items :[applicationTypeComboBox],
		buttons : [new Ext.Button({text : "Выбрать",
								   handler : function() {
									   if (applicationTypeComboBox.getValue() == "buy") {
										   addBuyApplicationForm.getForm().reset();
										   districtsComboBox.getStore().load();
										   whatAddWindowShows.setValue("buy");
										   choiseApplicationTypeWindow.hide();
										   addBuyApplicationWindow.show();
									   } else if(applicationTypeComboBox.getValue() == "sale"){
										   addSaleApplicationForm.getForm().reset();
										   addSaleDistrictsComboBox.getStore().load();
										   whatAddWindowShows.setValue("sale");
										   choiseApplicationTypeWindow.hide();
										   addSaleApplicationWindow.show();
									   }   
								   }}),
		           new Ext.Button({text : "Отмена",
		        	   			   handler : function(){
		        	   				   choiseApplicationTypeWindow.hide();
		        	   			   }})]
	});
	
	var choiseApplicationTypeWindow = new Ext.Window({	
			layout : 'fit',
			border : false,
			title : 'Выберите тип заявки',
			closeAction : 'hide',	
			y : 50,
			width : 340,
			height : 105,
			bodyStyle : "background-color:#CCD8E7",
			modal : true,
			items : [applicationTypeForm]
	});
	
	var saleApplicationsStore = applicationsStoreFactory.
									createApplicationStore("/flats/manager/get_sale_applications.do");
		
	var buyApplicationsStore = applicationsStoreFactory.
									createApplicationStore("/flats/manager/get_buy_applications.do");
	
	function removeApp(id) {
		deleteApplicationId.setValue(id);
		Ext.Msg.show({
				  title : "Удалить",
				  msg : "Вы уверены, что хотите удалить заявку?",
				  buttons : Ext.Msg.YESNO,
				  fn : function(btn) {
					if (btn == "yes") {		
						Ext.Ajax.request({
							url : "app/main/manager/delete_application",
							method : "post",
							params : {applicationId : deleteApplicationId.getValue()},
							success : function() {
								waintingAppStore.reload();
								applicationsStore.reload();
								Ext.Msg.alert("Удалено","Заявка успешно удалена!");
							},
							failure : function(){
								Ext.Msg.alert("Ошибка","Не могу удалить заявку!\nПопробуйте позже");
							}
						});
					} 
				  },
				  animEl : 'elId',
				  icon : Ext.MessageBox.QUESTION
		});
	}
	
	var buyApplicationDetailsWindow = new Ext.Window({	
		layout : 'fit',
		border : false,
		title : 'Детали заявки',
		closeAction : 'hide',	
		y : 50,
		width : 340,
		autoHeight : true,
		bodyStyle : "background-color:#CCD8E7",
		modal : true,
		items : [new Ext.FormPanel({
					border : false,
					bodyStyle : "background-color:#CCD8E7",
					height : 280,
					items : [new Ext.form.TextField({fieldLabel : "Фамилия",
													 readOnly : true,
													 id : "buyAppLastName",
													 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Имя",
								 					 readOnly : true,
								 					 id : "buyAppFirstName",
								 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Отчество",
								 					 readOnly : true,
								 					 id : "buyAppPatronymik",
								 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Телефон",
						    	 					 readOnly : true,
						    	 					 id : "buyAppPhone",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "E-mail",
						    	 					 readOnly : true,
						    	 					 id : "buyAppEmail",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Район",
						    	 					 readOnly : true,
						    	 					 id : "buyAppDistrict",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Этаж",
						    	 					 readOnly : true,
						    	 					 id : "buyAppFloor",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Комнат",
						    	 					 readOnly : true,
						    	 					 id : "buyAppRooms",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Цена от",
						    	 					 readOnly : true,
						    	 					 id : "buyAppPriceFrom",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Цена до",
						    	 					 readOnly : true,
						    	 					 id : "buyAppPriceTo",
						    	 					 width : 210})]
				 })]
	});		
	
	var saleApplicationDetailsWindow = new Ext.Window({	
		layout : 'fit',
		border : false,
		title : 'Детали заявки',
		closeAction : 'hide',	
		y : 50,
		width : 340,
		autoHeight : true,
		bodyStyle : "background-color:#CCD8E7",
		modal : true,
		items : [new Ext.FormPanel({
					border : false,
					bodyStyle : "background-color:#CCD8E7",
					height : 450,
					items : [new Ext.form.TextField({fieldLabel : "Фамилия",
													 readOnly : true,
													 id : "saleAppLastName",
													 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Имя",
								 					 readOnly : true,
								 					 id : "saleAppFirstName",
								 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Отчество",
								 					 readOnly : true,
								 					 id : "saleAppPatronymik",
								 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Телефон",
						    	 					 readOnly : true,
						    	 					 id : "saleAppPhone",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "E-mail",
						    	 					 readOnly : true,
						    	 					 id : "saleAppEmail",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Район",
						    	 					 readOnly : true,
						    	 					 id : "saleAppDistrict",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Этаж",
						    	 					 readOnly : true,
						    	 					 id : "saleAppFloor",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Этажей",
							   	 					 readOnly : true,
							   	 					 id : "saleAppFloorsCount",
							   	 					 width : 210}),	 					 
						     new Ext.form.TextField({fieldLabel : "Комнат",
						    	 					 readOnly : true,
						    	 					 id : "saleAppRooms",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Площадь",
							   	 					 readOnly : true,
							   	 					 id : "saleAppSquare",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Жилая площадь",
							   	 					 readOnly : true,
							   	 					 id : "saleAppLivingSpace",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Площадь кухни",
							   	 					 readOnly : true,
							   	 					 id : "saleAppCookSpace",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Улица",
							   	 					 readOnly : true,
							   	 					 id : "saleAppStreet",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Дом",
							   	 					 readOnly : true,
							   	 					 id : "saleAppHouse",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Квартира",
							   	 					 readOnly : true,
							   	 					 id : "saleAppFlat",
							   	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Цена",
						    	 					 readOnly : true,
						    	 					 id : "saleAppPrice",
						    	 					 width : 210})
						     ]
				 })]
	});
	
	function saleAppDetails(id) {
		Ext.Ajax.request({
			url : "/flats/manager/get_saleapplication_details.do",
			params : {applicationId:id},
			success : function(response) {
				var data = Ext.decode(response.responseText);
				Ext.getCmp("saleAppLastName").setValue(data.client.lastName);
				Ext.getCmp("saleAppFirstName").setValue(data.client.firstName);
				Ext.getCmp("saleAppPatronymik").setValue(data.client.patronymik);
				Ext.getCmp("saleAppPhone").setValue(data.client.phone);
				Ext.getCmp("saleAppEmail").setValue(data.client.email);
				Ext.getCmp("saleAppDistrict").setValue(data.flat.district.name);
				Ext.getCmp("saleAppFloor").setValue(data.flat.floor);
				Ext.getCmp("saleAppFloorsCount").setValue(data.flat.floors);
				Ext.getCmp("saleAppRooms").setValue(data.flat.rooms);
				Ext.getCmp("saleAppSquare").setValue(data.flat.square);
				Ext.getCmp("saleAppLivingSpace").setValue(data.flat.livingSquare);
				Ext.getCmp("saleAppCookSpace").setValue(data.flat.cookSquare);
				Ext.getCmp("saleAppStreet").setValue(data.flat.street);
				Ext.getCmp("saleAppHouse").setValue(data.flat.house);
				Ext.getCmp("saleAppFlat").setValue(data.flat.flat);
				Ext.getCmp("saleAppPrice").setValue(data.flat.price);
				saleApplicationDetailsWindow.show();
			},
			failure : function() {
				Ext.Msg.alert("Ошибка","Не могу получить данные о заявке! Попробуйте позже.");
			}
		});
	}
	

	function buyAppDetails(id) {		
		Ext.Ajax.request({
			url : "/flats/manager/get_buyapplication_details.do",
			method : 'post',
			params : {applicationId:id},
			success : function(response) {
				var data = Ext.decode(response.responseText);					
			    Ext.getCmp("buyAppLastName").setValue(data.client.lastName);
				Ext.getCmp("buyAppFirstName").setValue(data.client.firstName);
				Ext.getCmp("buyAppPatronymik").setValue(data.client.patronymik);
				Ext.getCmp("buyAppPhone").setValue(data.client.phone);
				Ext.getCmp("buyAppEmail").setValue(data.client.email);
				Ext.getCmp("buyAppDistrict").setValue(data.district.name);
				if (data.floor > 0) {
					Ext.getCmp("buyAppFloor").setValue(data.floor);
				}
				Ext.getCmp("buyAppRooms").setValue(data.rooms);
				if (data.priceFrom > 0) {
					Ext.getCmp("buyAppPriceFrom").setValue(data.priceFrom);
				}
				Ext.getCmp("buyAppPriceTo").setValue(data.priceTo);
				buyApplicationDetailsWindow.show();
			},
			failure : function() {
				Ext.Msg.alert("Ошибка","Не могу получить данные о заявке! Попробуйте позже.");
			}
		});
	}
	
	var deleteApplicationId = new Ext.form.Field({hidden : true});
	
	function removeBuyApp(id) {
		deleteApplicationId.setValue(id);
		Ext.Msg.show({
				  title : "Удалить",
				  msg : "Вы уверены, что хотите удалить заявку?",
				  buttons : Ext.Msg.YESNO,
				  fn : function(btn) {
					if (btn == "yes") {		
						Ext.Ajax.request({
							url : "/flats/manager/remove_buy_app.do",
							method : "post",
							params : {id : deleteApplicationId.getValue()},
							success : function() {
								waintingAppStore.reload();
								buyApplicationsStore.reload();								
								Ext.Msg.alert("Удалено","Заявка успешно удалена!");
							},
							failure : function(){
								Ext.Msg.alert("Ошибка","Не могу удалить заявку! Попробуйте позже");
							}
						});
					} 
				  },
				  animEl : 'elId',
				  icon : Ext.MessageBox.QUESTION
		});
	}
	
	function removeSaleApp(id) {
		deleteApplicationId.setValue(id);
		Ext.Msg.show({
				  title : "Удалить",
				  msg : "Вы уверены, что хотите удалить заявку?",
				  buttons : Ext.Msg.YESNO,
				  fn : function(btn) {
					if (btn == "yes") {		
						Ext.Ajax.request({
							url : "/flats/manager/remove_sale_app.do",
							method : "post",
							params : {id : deleteApplicationId.getValue()},
							success : function() {
								saleApplicationsStore.reload();								
								Ext.Msg.alert("Удалено","Заявка успешно удалена!");
							},
							failure : function(){
								Ext.Msg.alert("Ошибка","Не могу удалить заявку! Попробуйте позже");
							}
						});
					} 
				  },
				  animEl : 'elId',
				  icon : Ext.MessageBox.QUESTION
		});
	}
	
	var buyApplicationsGrid = new Ext.grid.GridPanel({	
		store : buyApplicationsStore,
		columnLines : true,	
		height : 600,
		border:false,
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex:'id',header : "Номер заявки"},
		           {sortable : true,dataIndex:'createDate',header:'Дата'},
		           {sortable : true,dataIndex:'client.lastName',header:'Фамилия'},
		           {sortable : true,dataIndex:'client.firstName',header:'Имя'},
		           {sortable : true,dataIndex:'client.patronymik',header:'Отчество'},		           
		           {sortable : true,header : "Подробнее",renderer : function(val,object,row) {
		        	   return '<button onclick="buyAppDetails('+row.data['id']+')" >Подробнее</button>';		         	   
		       	   }},
		           {sortable : false,header : "Удалить",renderer : function(val,object,row) {
		        	   var button = '<button onclick="removeBuyApp('+row.data['id']+')" ';		         	   
		         	   button += '>Удалить</button>';
		         	   return button;
		        	}},
		        	{sortable :false,header : "Подобрать варианты",renderer : function(val,object,row){
		        		var button = '<button onclick="choiseSuitableOptions(' + row.data['id'] + 
		        		')"';		        		
		        		button += '>Подобрать</button>';
		        		return button;
		        	}}],
		bbar : new Ext.PagingToolbar({
			pageSize : 20,
			store : buyApplicationsStore
		})
	});
	
	var saleApplicationsGrid = new Ext.grid.GridPanel({	
		store : saleApplicationsStore,
		columnLines : true,	
		height : 600,
		border:false,
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex:'id',header : "Номер заявки"},
		           {sortable : true,dataIndex:'createDate',header:'Дата'},
		           {sortable : true,dataIndex:'client.lastName',header:'Фамилия'},
		           {sortable : true,dataIndex:'client.firstName',header:'Имя'},
		           {sortable : true,dataIndex:'client.patronymik',header:'Отчество'},		           
		           {sortable : true,header : "Подробнее",renderer : function(val,object,row) {
		        	   return '<button onclick="saleAppDetails('+row.data['id']+')" >Подробнее</button>';		         	   
		       	   }},
		           {sortable : false,header : "Удалить",renderer : function(val,object,row) {
		        	   return '<button onclick="removeSaleApp('+row.data['id']+')">Удалить</button>';    	   
		        	}}],
		bbar : new Ext.PagingToolbar({
			pageSize : 20,
			store : buyApplicationsStore
		})
	});
	
	var waintingAppStore = new Ext.data.JsonStore({
		url : "/flats/manager/wainting_apps.do",
		fields : ["client.lastName","client.firstName","client.patronymik","createDate","id"],
		root : "applications",
		totalProperty: 'count'
	});
	
	var suitableOptionsGrid = new Ext.grid.GridPanel({
		store : new Ext.data.JsonStore({
					url : "/flats/manager/get_suitable_options.do",
					fields : ["status","flat.street","flat.house","flat.flat","flat.rooms","id","flat.price"]					
				}),
		border :false,
		height : 500,
		columnLines : true,
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex : "status",header : "Статус",renderer : function(value) {
						switch (value) {
							case "NONE": return "";break;
							case "GOOD": return "Хорошо";break;
							case "BAD": return "Плохо";break;
							case "NORMAL": return "Нормально";break;
						}
				   }},
		           {sortable : true,dataIndex : "flat.street",header : "Улица"},
		           {sortable : true,dataIndex : "flat.house",header : "Дом"},
		           {sortable : true,dataIndex : "flat.flat",header : "Квартира"},
		           {sortable : true,dataIndex : "flat.rooms",header : "Комнат"},
		           {sortable : true,dataIndex : "flat.price",header : "Цена"},		           
		           {sortable : false,header : "Подробнее",renderer : function(val,object,row) {
		        	   return '<button onclick="appDetails('+row.data['id']+',\'sale\')" >Подробнее</button>';
		           }}]
	});
	
	var currentSuitableOptionsId = new Ext.form.Field({hidden:true});
	
	var suitableOptionsWindow = new Ext.Window({
		layout : 'fit',
		title : 'Подходящие варианты',
		closeAction : 'hide',		
		y : 35,
		width : 820,
		modal : true,
		autoHeight : true,
		viewConfig : {forceFit : true},
		items : [ new Ext.Panel({border:false,
								 autoHeight : true,
							     viewConfig : {forceFit : true},
							     items :[new Ext.Panel({border :false,
										                tbar:[new Ext.Button({text : "Подробности заявки",
										                					  handler : function() {
										                						  		var id = currentSuitableOptionsId.getValue();
										                						  		buyApplicationDetailsWindow.modal = false;
										                						  		appDetails(id,"buy");
										                	   }}),
										                	   "-",
										                	   new Ext.Button({text : "Подобрать варианты",
										                		   			   handler : function() {
										                		   				   		var id = currentSuitableOptionsId.getValue();
										                		   				   		Ext.Ajax.request({
										                		   				   			method : "post",
										                		   				   			params : {applicationId:id},
										                		   				   			url : "app/main/manager/find_suitable_options",
										                		   				   			success : function() {
										                		   				   				suitableOptionsGrid.getStore().reload();
										                		   				   			},
										                		   				   			failure : function(){
										                		   				   				Ext.Msg.alert("Ошибка","Не могу подобрать варианты! Попробуйте позже.");
										                		   				   			}
										                		   				   		});
										                		   			   }})]}),
									     suitableOptionsGrid]}) ],
        listeners : {
        	hide : function() {
        		buyApplicationDetailsWindow.modal = true;
        	}
        }
	});
	
	function choiseSuitableOptions(id) {
		currentSuitableOptionsId.setValue(id);
		suitableOptionsGrid.getStore().load({params:{id:id}});
		suitableOptionsWindow.show();
	}
	
	var waintingApplicationsGrid = new Ext.grid.GridPanel({	
		store : waintingAppStore,
		columnLines : true,	
		height : 600,
		border:false,
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex:'id',header : "Номер заявки"},
		           {sortable : true,dataIndex:'createDate',header:'Дата'},
		           {sortable : true,dataIndex:'client.lastName',header:'Фамилия'},
		           {sortable : true,dataIndex:'client.firstName',header:'Имя'},
		           {sortable : true,dataIndex:'client.patronymik',header:'Отчество'},		           
		           {sortable : true,header : "Подробнее",renderer : function(val,object,row) {
		        	   return '<button onclick="buyAppDetails('+row.data['id']+')" >Подробнее</button>';		         	   
		       	   }},
		           {sortable : false,header : "Удалить",renderer : function(val,object,row) {
		        	   return '<button onclick="removeBuyApp('+row.data['id']+')">Удалить</button>';		         	   
		        	}},
		        	{sortable :false,header : "Подобрать варианты",renderer : function(val,object,row){
		        		return '<button onclick="choiseSuitableOptions(' + row.data['id'] + ')">Подобрать</button>';
		        	}}],
		bbar : new Ext.PagingToolbar({
			pageSize : 20,
			store : waintingAppStore
		})
	});
	
	var buyApplicationsWindow = appWindowFactory.createApplicationWindow("Заявки на покупку",
			buyApplicationsGrid);
	
	var saleApplicationsWindow = appWindowFactory.createApplicationWindow("Заявки на продажу", 
			saleApplicationsGrid);
	
	var waitingApplicationsWindow = new Ext.Window({
		layout : 'fit',
		title : 'Ожидающие заявка',
		closeAction : 'hide',	
		x : 10,
		y : 35,
		width : 1260,
		autoHeight : true,
		viewConfig : {forceFit : true},
		items : [ new Ext.Panel({border:false,
								 autoHeight : true,
							     viewConfig : {forceFit : true},
							     items :[waintingApplicationsGrid]}) ]
	});
		
Ext.onReady(function() {
	Ext.QuickTips.init();
	var applicationMenu = new Ext.Panel({
		border :false,
		viewConfig : {forceFit : true},
		tbar:[new Ext.Button({text : 'Создать заявку',
							  handler : function() {
								applicationTypeComboBox.getStore().loadData(applicationTypeData);
								choiseApplicationTypeWindow.show();  
							  }}),"-",
			  new Ext.Button({text : "Покупка",
				              handler : function() {
				            	  buyApplicationsStore.load({params:{start:0,limit:20}});
				            	  buyApplicationsWindow.show();
				              }}),"-",
			  new Ext.Button({text : "Продажа",
				  		      handler : function() {
				  		    	saleApplicationsStore.load({params:{start:0,limit:20}});				  		    	
				  		    	saleApplicationsWindow.show();
				  		      }}),"-",
			  new Ext.Button({text : "Ожидающие заявки",
				  			  handler : function(){
				  				waintingAppStore.load({params:{start:0,limit:20}});
				  				waitingApplicationsWindow.show();
				  			  }}),	  		      
				  		      '->',
			  new Ext.Button({text : 'Выход',
				  			  handler : function() {
				  				  Ext.Msg.show({
				  					  title : "Выход",
				  					  msg : "Вы уверены, что хотите выйти?",
				  					  buttons : Ext.Msg.YESNO,
				  					  fn : function(btn) {
											if (btn == "yes") {							
												document.location.href="http://localhost:8080/flats/logout.do";
											} 
				  					  },
				  					  animEl : 'elId',
				  					  icon : Ext.MessageBox.QUESTION
				  				  });
				  			  }})],
		height : 20,
		renderTo : Ext.get("menu")
	});

	
});